package flex.cc.vehicle_svr.controller;

import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.common.utils.DateUtil;
import flex.cc.core.support.BaseController;
import flex.cc.order.manage.dto.order.OrderMainEntity;
import flex.cc.order.manage.service.OrderMainService;
import flex.cc.order.manage.service.OrderTrackService;
import flex.cc.util.EncryptionDecryption;

/**
 * 上游催单接口
 */
@RestController
@RequestMapping(value = "/vehicleSvr")
public class UrgeController extends BaseController {

	@Resource
	private OrderTrackService orderTrackService;
	@Resource
	private OrderMainService orderMainService;
	
    /**
	 * 
	 * @author WANGCONG
	 * 2021年9月7日上午10:42:08
	 * @desc 上游催单
	 * @desc 下游接口返回：{"resultCode":1,"message":"救援任务不存在"}
	 */
    @SuppressWarnings("static-access")
	@ResponseBody
    @RequestMapping("/urgeOrder")
    public String urgeOrder(HttpServletRequest request) throws Exception {
        // 进入接口时间
        long startTime = System.currentTimeMillis();
        logger.info("vehicleSvr/urgeOrder 进入接口:time=" + DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
        Boolean flag = true;
        String responseMsg = "成功";
        JSONObject jsonResult = new JSONObject();
        EncryptionDecryption des = new EncryptionDecryption();
        //读取报文
        try {
            // 设置编码
            request.setCharacterEncoding("UTF-8");
            // 读取请求报文
            String requestJson = IOUtils.toString(request.getInputStream(), "UTF-8");
            requestJson = URLDecoder.decode(requestJson, "UTF-8");
            if (requestJson != null && !"".equals(requestJson)) {
                // 调用业务处理 =============================
            	logger.info("vehicleSvr/urgeOrder requestJson:" + requestJson);
            	requestJson = des.decrypt(requestJson, "UTF-8");
            	logger.info("催单报文解密后=" + requestJson);
                JSONObject jsonObject = JSONObject.parseObject(requestJson);
                JSONObject requestHeader = (JSONObject)jsonObject.get("requestHeader");
                JSONObject requestBody = (JSONObject)jsonObject.get("requestBody");
                Map requestHeaderMap = requestHeader.toJavaObject(Map.class);
                String requestCode = PublicUtil.isNotEmpty(requestHeaderMap.get("requestCode")) ? requestHeaderMap.get("requestCode").toString() : null;
                if ("urgingRescue".equals(requestCode)) {
                	Map<String, Object> postJson = new HashMap<>(); 
    	            postJson.put("orderNo", PublicUtil.isNotEmpty(requestBody.get("ownerOrderNo")) ? requestBody.get("ownerOrderNo").toString() : "");
    	            postJson.put("content", PublicUtil.isNotEmpty(requestBody.get("serviceContent")) ? requestBody.get("serviceContent").toString() : "");
    	            postJson.put("flag", "1"); //1代表上游的，0代表页面操作的
    	            Map<String, Object> order_param = new HashMap<>();
    				order_param.put("ownerOrderNo", (String)postJson.get("orderNo"));
    				OrderMainEntity orderMain = orderMainService.getOneByParams(order_param);
    				String orderStatus = orderMain.getStatus();
    				if(orderStatus=="00"||orderStatus=="01"||orderStatus=="08"||orderStatus=="09"||orderStatus=="10"||orderStatus=="11"){
    					flag = false;
    					responseMsg = "催单失败，服务单状态不满足催单条件";
    		   		}else{
    		   			Map<String, Object> urgeResult = orderTrackService.urgeOrder(postJson);
        	            String resultCode = urgeResult.get("responseCode").toString();
        	            if("00".equals(resultCode)){
        	            	flag = true;
                            responseMsg = "催单成功";
        	            }else{
        	            	flag = false;
                            responseMsg = PublicUtil.isNotEmpty(urgeResult.get("message")) ? urgeResult.get("message").toString() : "失败";
        	            }
    		   		}
                }

            } else {
                flag = false;
                responseMsg = "接口处理异常:请求报文为空";
                logger.error("vehicleSvr/urgeOrder 接口处理异常:请求报文为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            responseMsg = "数据接收异常";
            logger.error("vehicleSvr/urgeOrder 数据接收异常:" + e.getMessage());
        }
        if(flag){
            jsonResult.put("responseCode", "00");
        } else {
        	jsonResult.put("responseCode", "01");
        }
        jsonResult.put("responseMsg", responseMsg);
        // 离开接口时间
        long endTime = System.currentTimeMillis();
        logger.info("vehicleSvr/urgeOrder 离开接口:time=" + DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + ";处理时长:" + (endTime - startTime));
        String jsonStr = JSONObject.toJSONString(jsonResult);
        return des.encrypt(jsonStr);
    }
    
}
